package com.arpa.ntocc.common.license;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Component
public class CommonSdk {
	/** 心跳间隔（单位：秒） */
	public static final Long SLEEP_SECONDS = 60L;
	public static final String MESSAGE_TIP_KEY = "arpa-tip";
	
	static {
		Thread a = new Thread(new Runnable() {

			public void run() {
				while (true) {
					try {
						HttpPost post = new HttpPost("http://cloud.kuaituo.com/arpa-cloud-api-license/licenseCheck/heartbeat?customerCode=customerCode");
						
						CloseableHttpResponse response =  HttpClients.createDefault().execute(post);
						
						if(response.getStatusLine().getStatusCode()==200){
							String result=EntityUtils.toString(response.getEntity(), "UTF-8");
							System.out.println(result);
							if(result.contains("SHUT_DOWN")) {
								System.exit(0);
								break;
							} else if(result.contains("EXPIRATION_WARNING")) {
								String prefix = "\"message\":\"";
								int start = result.indexOf(prefix) + prefix.length();
								int end = result.indexOf("\"", start);
								String message = result.substring(start , end);
								System.out.println(message);
								System.setProperty(CommonSdk.MESSAGE_TIP_KEY, message);
							} else {
								System.getProperties().remove(CommonSdk.MESSAGE_TIP_KEY);
							}
						}
					} catch (Exception a) {
					}
					try {
						Thread.sleep(CommonSdk.SLEEP_SECONDS * 1000L);
					} catch (Exception a) {
					}
				}
			}

		});
		a.setName("ArpaHeartBeat");
		a.start();
	}

}
